package formatter

import (
    "fmt"
    "strings"
    "time"

    "sysinfo/internal/types"

    "github.com/fatih/color"
)

// FormatPretty 使用颜色和表格格式化信息
func FormatPretty(info *types.SystemInfo) string {
	var sb strings.Builder

	// Color definitions
	headerColor := color.New(color.FgCyan, color.Bold)
	labelColor := color.New(color.FgGreen)
	valueColor := color.New(color.FgWhite)

	// Timestamp
	sb.WriteString(headerColor.Sprintf("═══════════════════════════════════════════════════════════════\n"))
	sb.WriteString(headerColor.Sprintf("  系统信息报告\n"))
	sb.WriteString(headerColor.Sprintf("═══════════════════════════════════════════════════════════════\n"))
	sb.WriteString(fmt.Sprintf("%s %s\n\n", labelColor.Sprint("时间戳:"), valueColor.Sprint(info.Timestamp.Format("2006-01-02 15:04:05"))))

	// System information
	if info.System != nil {
		sb.WriteString(headerColor.Sprintf("┌─ 系统信息 ────────────────────────────────────────────────────┐\n"))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("主机名:"), valueColor.Sprint(info.System.Hostname)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("操作系统:"), valueColor.Sprint(info.System.OS)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s %s\n", labelColor.Sprint("平台:"), valueColor.Sprint(info.System.Platform), valueColor.Sprint(info.System.PlatformVersion)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("内核:"), valueColor.Sprintf("%s (%s)", info.System.KernelVersion, info.System.KernelArch)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("运行时间:"), valueColor.Sprint(info.System.UptimeFormatted)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("进程数:"), valueColor.Sprintf("%d", info.System.Procs)))
		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// CPU information
	if info.CPU != nil {
		sb.WriteString(headerColor.Sprintf("┌─ CPU ────────────────────────────────────────────────────────┐\n"))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("型号:"), valueColor.Sprint(info.CPU.ModelName)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("制造商:"), valueColor.Sprint(info.CPU.Vendor)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("物理核心:"), valueColor.Sprintf("%d", info.CPU.Cores)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("逻辑CPU:"), valueColor.Sprintf("%d", info.CPU.LogicalCPUs)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("频率:"), valueColor.Sprintf("%.2f MHz", info.CPU.MHz)))

		if info.CPU.CacheSize > 0 {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("缓存大小:"), valueColor.Sprintf("%d KB", info.CPU.CacheSize)))
		}

		if info.CPU.Microcode != "" {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("微码:"), valueColor.Sprint(info.CPU.Microcode)))
		}

		if info.CPU.LoadAvg != nil {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("负载均衡:"),
				valueColor.Sprintf("%.2f, %.2f, %.2f", info.CPU.LoadAvg.Load1, info.CPU.LoadAvg.Load5, info.CPU.LoadAvg.Load15)))
		}

		if len(info.CPU.Usage) > 0 {
			sb.WriteString(fmt.Sprintf("│ %-20s\n", labelColor.Sprint("核心使用率:")))
			for i, usage := range info.CPU.Usage {
				bar := createProgressBar(usage, 20)
				sb.WriteString(fmt.Sprintf("│   核心 %-2d: %s %s\n", i, bar, valueColor.Sprintf("%.1f%%", usage)))
			}
		}
		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// Memory information
	if info.Memory != nil {
		sb.WriteString(headerColor.Sprintf("┌─ 内存 ──────────────────────────────────────────────────────┐\n"))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("总容量:"), valueColor.Sprint(info.Memory.TotalFormatted)))

		memBar := createProgressBar(info.Memory.UsedPercent, 30)
		sb.WriteString(fmt.Sprintf("│ %-20s %s %s\n", labelColor.Sprint("已用:"),
			memBar, valueColor.Sprintf("%s (%.1f%%)", info.Memory.UsedFormatted, info.Memory.UsedPercent)))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("可用:"), valueColor.Sprint(info.Memory.FreeFormatted)))

		if info.Memory.Cached > 0 {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("缓存:"), valueColor.Sprint(formatBytes(info.Memory.Cached))))
		}
		if info.Memory.Buffers > 0 {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("缓冲:"), valueColor.Sprint(formatBytes(info.Memory.Buffers))))
		}

		if info.Memory.SwapTotal > 0 {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("交换分区总容量:"), valueColor.Sprint(formatBytes(info.Memory.SwapTotal))))
			swapBar := createProgressBar(info.Memory.SwapPercent, 30)
			sb.WriteString(fmt.Sprintf("│ %-20s %s %s\n", labelColor.Sprint("交换分区已用:"),
				swapBar, valueColor.Sprintf("%s (%.1f%%)", formatBytes(info.Memory.SwapUsed), info.Memory.SwapPercent)))
		}

		if len(info.Memory.Modules) > 0 {
			sb.WriteString(fmt.Sprintf("│\n│ %s\n", labelColor.Sprint("物理内存模块:")))
			for _, module := range info.Memory.Modules {
				sb.WriteString(fmt.Sprintf("│   %s\n", valueColor.Sprintf("%s: %s", module.Locator, formatBytes(module.Capacity))))
				if module.Speed > 0 {
					sb.WriteString(fmt.Sprintf("│     速度: %s, 类型: %s\n", valueColor.Sprintf("%d MHz", module.Speed), valueColor.Sprint(module.Type)))
				}
			}
		}

		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// Disk information
	if info.Disk != nil {
		sb.WriteString(headerColor.Sprintf("┌─ 存储 ──────────────────────────────────────────────────────┐\n"))

		// Physical disks information first (the actual hardware)
		if len(info.Disk.PhysicalDisks) > 0 {
			sb.WriteString(fmt.Sprintf("│ %s\n", labelColor.Sprint("物理磁盘:")))
			sb.WriteString("│\n")
			for _, disk := range info.Disk.PhysicalDisks {
				diskType := disk.Type
				if disk.Type == "" {
					diskType = "未知"
				}

				// Show disk name and type
				sb.WriteString(fmt.Sprintf("│ %s [%s]", valueColor.Sprint(disk.Name), valueColor.Sprint(diskType)))
				if disk.Interface != "" {
					sb.WriteString(fmt.Sprintf(" %s", color.New(color.FgCyan).Sprint(disk.Interface)))
				}
				sb.WriteString("\n")

				// Show model
				if disk.Model != "" {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("型号:"), valueColor.Sprint(disk.Model)))
				}

				// Show size
				if disk.SizeFormatted != "" && disk.SizeFormatted != "N/A" {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("容量:"), valueColor.Sprint(disk.SizeFormatted)))
				}

				// Show serial number
				if disk.SerialNumber != "" {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("序列号:"), valueColor.Sprint(disk.SerialNumber)))
				}

				// Show RPM for HDDs
				if disk.RPM > 0 {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("转速:"), valueColor.Sprintf("%d RPM", disk.RPM)))
				}

				// Show removable status
				if disk.Removable {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("可移动:"), color.New(color.FgYellow).Sprint("是")))
				}

				sb.WriteString("│\n")
			}
		}

		// Mounted partitions (filter out loop devices and snaps for cleaner output)
		if len(info.Disk.Partitions) > 0 {
			// Filter significant partitions
			var significantPartitions []types.PartitionInfo
			for _, part := range info.Disk.Partitions {
				// Skip loop devices (snap mounts) and very small partitions
				if strings.HasPrefix(part.Device, "/dev/loop") {
					continue
				}
				// Skip if squashfs (usually snaps)
				if part.FSType == "squashfs" {
					continue
				}
				significantPartitions = append(significantPartitions, part)
			}

			if len(significantPartitions) > 0 {
				sb.WriteString(fmt.Sprintf("│ %s\n", labelColor.Sprint("挂载分区:")))
				sb.WriteString("│\n")
				for _, part := range significantPartitions {
					sb.WriteString(fmt.Sprintf("│ %s", valueColor.Sprintf("%s", part.Device)))
					if part.MountPoint != "" {
						sb.WriteString(fmt.Sprintf(" → %s", valueColor.Sprintf("%s", part.MountPoint)))
					}
					sb.WriteString("\n")

					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("类型:"), valueColor.Sprint(part.FSType)))
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("总容量:"), valueColor.Sprint(part.TotalFormatted)))

					diskBar := createProgressBar(part.UsedPercent, 28)
					sb.WriteString(fmt.Sprintf("│   %-18s %s %s\n", labelColor.Sprint("已用:"),
						diskBar, valueColor.Sprintf("%s (%.1f%%)", part.UsedFormatted, part.UsedPercent)))
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("可用:"), valueColor.Sprint(part.FreeFormatted)))
					sb.WriteString("│\n")
				}
			}
		}

		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// SMART disk health information
	if info.Disk != nil && len(info.Disk.SMARTData) > 0 {
		sb.WriteString(headerColor.Sprintf("┌─ 磁盘健康状态(SMART) ───────────────────────────────────────┐\n"))
		for _, smart := range info.Disk.SMARTData {
			deviceName := smart.Device
			if smart.DeviceModel != "" {
				deviceName = smart.DeviceModel
			}

			healthStatus := "健康"
			healthColor := color.New(color.FgGreen, color.Bold)
			if !smart.Healthy {
				healthStatus = "警告"
				healthColor = color.New(color.FgRed, color.Bold)
			}

			sb.WriteString(fmt.Sprintf("│ %s [%s]\n", valueColor.Sprint(deviceName), healthColor.Sprint(healthStatus)))

			if smart.Serial != "" {
				sb.WriteString(fmt.Sprintf("│   %-20s %s\n", labelColor.Sprint("序列号:"), valueColor.Sprint(smart.Serial)))
			}
			if smart.Capacity > 0 {
				sb.WriteString(fmt.Sprintf("│   %-20s %s\n", labelColor.Sprint("容量:"), valueColor.Sprint(formatBytes(smart.Capacity))))
			}
			if smart.Temperature > 0 {
				tempColor := valueColor
				if smart.Temperature > 50 {
					tempColor = color.New(color.FgYellow)
				}
				if smart.Temperature > 60 {
					tempColor = color.New(color.FgRed)
				}
				sb.WriteString(fmt.Sprintf("│   %-20s %s\n", labelColor.Sprint("温度:"), tempColor.Sprintf("%d°C", smart.Temperature)))
			}
			if smart.PowerOnHours > 0 {
				days := smart.PowerOnHours / 24
				sb.WriteString(fmt.Sprintf("│   %-20s %s (%s 天)\n",
					labelColor.Sprint("运行时间:"),
					valueColor.Sprintf("%d 小时", smart.PowerOnHours),
					valueColor.Sprintf("%d", days)))
			}

			// Display key SMART attributes
			if len(smart.Attributes) > 0 {
				// Show critical attributes
				criticalAttrs := []string{
					"Reallocated_Sector_Count",
					"Current_Pending_Sector",
					"Offline_Uncorrectable",
					"UDMA_CRC_Error_Count",
				}

				hasShownAttrs := false
				for _, attrName := range criticalAttrs {
					if val, ok := smart.Attributes[attrName]; ok && val != "0" {
						if !hasShownAttrs {
							sb.WriteString(fmt.Sprintf("│   %s\n", labelColor.Sprint("关键属性:")))
							hasShownAttrs = true
						}
						warnColor := color.New(color.FgYellow)
						sb.WriteString(fmt.Sprintf("│     %s: %s\n", attrName, warnColor.Sprint(val)))
					}
				}
			}

			sb.WriteString("│\n")
		}
		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// Network information
	if info.Network != nil && len(info.Network.Interfaces) > 0 {
		sb.WriteString(headerColor.Sprintf("┌─ 网络 ──────────────────────────────────────────────────────┐\n"))
		for _, iface := range info.Network.Interfaces {
			sb.WriteString(fmt.Sprintf("│ %s\n", valueColor.Sprint(iface.Name)))
			if iface.HardwareAddr != "" {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("MAC地址:"), valueColor.Sprint(iface.HardwareAddr)))
			}
			if len(iface.Addresses) > 0 {
				for i, addr := range iface.Addresses {
					if i == 0 {
						sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("IP地址:"), valueColor.Sprint(addr)))
					} else {
						sb.WriteString(fmt.Sprintf("│   %-18s %s\n", "", valueColor.Sprint(addr)))
					}
				}
			}
			if iface.BytesSent > 0 || iface.BytesRecv > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("发送:"), valueColor.Sprint(formatBytes(iface.BytesSent))))
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("接收:"), valueColor.Sprint(formatBytes(iface.BytesRecv))))
			}
			sb.WriteString("│\n")
		}
		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// Ports information
	if info.Ports != nil {
		sb.WriteString(headerColor.Sprintf("┌─ 端口 ──────────────────────────────────────────────────────┐\n"))
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("监听总数:"), valueColor.Sprintf("%d", info.Ports.TotalListening)))
		sb.WriteString("│\n")

		max := len(info.Ports.Entries)
		if max > 20 {
			max = 20
		}
		for i := 0; i < max; i++ {
			e := info.Ports.Entries[i]
			proto := strings.ToUpper(e.Protocol)
			ip := e.LocalIP
			if ip == "" {
				ip = "0.0.0.0"
			}
			pidStr := ""
			if e.PID > 0 {
				pidStr = fmt.Sprintf(" PID %d", e.PID)
			}
			procStr := ""
			if e.ProcessName != "" {
				procStr = fmt.Sprintf(" (%s)", e.ProcessName)
			}
			sb.WriteString(fmt.Sprintf("│   %s\n", valueColor.Sprintf("%-4s %s:%d%s%s", proto, ip, e.LocalPort, pidStr, procStr)))
		}

		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n\n"))
	}

	// Process information
	if info.Processes != nil {
		sb.WriteString(headerColor.Sprintf("┌─ 进程 ──────────────────────────────────────────────────────┐\n"))
		sb.WriteString(fmt.Sprintf("│ %-20s %s (运行中: %s, 睡眠: %s)\n",
			labelColor.Sprint("总计:"),
			valueColor.Sprintf("%d", info.Processes.TotalCount),
			valueColor.Sprintf("%d", info.Processes.Running),
			valueColor.Sprintf("%d", info.Processes.Sleeping)))

		if len(info.Processes.TopByMemory) > 0 {
			sb.WriteString(fmt.Sprintf("│\n│ %s\n", labelColor.Sprint("内存占用排行:")))
			for i, proc := range info.Processes.TopByMemory {
				if i >= 5 {
					break
				}
				sb.WriteString(fmt.Sprintf("│   %s\n", valueColor.Sprintf("%-30s %6d MB  %.1f%%",
					truncate(proc.Name, 30), proc.MemoryMB, proc.MemoryPercent)))
			}
		}

		if len(info.Processes.TopByCPU) > 0 {
			sb.WriteString(fmt.Sprintf("│\n│ %s\n", labelColor.Sprint("CPU占用排行:")))
			for i, proc := range info.Processes.TopByCPU {
				if i >= 5 {
					break
				}
				sb.WriteString(fmt.Sprintf("│   %s\n", valueColor.Sprintf("%-30s %6.1f%%",
					truncate(proc.Name, 30), proc.CPUPercent)))
			}
		}

		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n"))
	}

	// Battery information
	if info.Battery != nil && info.Battery.Present && len(info.Battery.Batteries) > 0 {
		sb.WriteString("\n")
		sb.WriteString(headerColor.Sprintf("┌─ 电池 ──────────────────────────────────────────────────────┐\n"))

		// Power source status
		powerSource := "交流电源"
		if info.Battery.OnBattery {
			powerSource = color.New(color.FgYellow).Sprint("电池供电")
		}
		sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("电源来源:"), powerSource))

		if len(info.Battery.Batteries) > 1 {
			sb.WriteString(fmt.Sprintf("│ %-20s %s\n", labelColor.Sprint("总容量:"),
				valueColor.Sprint(formatMilliwattHours(info.Battery.TotalCapacity))))
		}
		sb.WriteString("│\n")

		for i, battery := range info.Battery.Batteries {
			if i > 0 {
				sb.WriteString("│\n")
			}

			batteryLabel := battery.Name
			if battery.Model != "" {
				batteryLabel = fmt.Sprintf("%s (%s)", battery.Name, battery.Model)
			}
			sb.WriteString(fmt.Sprintf("│ %s\n", valueColor.Sprint(batteryLabel)))

			// State with color
			stateColor := valueColor
			switch battery.State {
			case "Charging":
				stateColor = color.New(color.FgGreen)
			case "Discharging":
				stateColor = color.New(color.FgYellow)
			case "Full":
				stateColor = color.New(color.FgCyan)
			case "Critical", "Low":
				stateColor = color.New(color.FgRed)
			}
			sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("状态:"), stateColor.Sprint(battery.State)))

			// Charge level with progress bar
			if battery.ChargeLevel > 0 {
				chargeBar := createProgressBar(battery.ChargeLevel, 28)
				chargeColor := valueColor
				if battery.ChargeLevel < 20 {
					chargeColor = color.New(color.FgRed)
				} else if battery.ChargeLevel < 50 {
					chargeColor = color.New(color.FgYellow)
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s %s\n", labelColor.Sprint("电量:"),
					chargeBar, chargeColor.Sprintf("%.1f%%", battery.ChargeLevel)))
			}

			// Health with progress bar
			if battery.Health > 0 {
				healthBar := createProgressBar(battery.Health, 28)
				healthColor := valueColor
				if battery.Health < 60 {
					healthColor = color.New(color.FgRed)
				} else if battery.Health < 80 {
					healthColor = color.New(color.FgYellow)
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s %s\n", labelColor.Sprint("电池健康:"),
					healthBar, healthColor.Sprintf("%.1f%%", battery.Health)))
			}

			// Time remaining
			if battery.TimeRemaining >= 0 {
				timeStr := formatTime(battery.TimeRemaining)
				if battery.IsCharging {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("充满时间:"), valueColor.Sprint(timeStr)))
				} else if battery.IsDischarging {
					sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("剩余时间:"), valueColor.Sprint(timeStr)))
				}
			}

			// Capacity information
			if battery.CapacityFull > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("当前容量:"),
					valueColor.Sprintf("%s / %s",
						formatMilliwattHours(battery.CapacityNow),
						formatMilliwattHours(battery.CapacityFull))))
			}

			if battery.Capacity > 0 && battery.Capacity != battery.CapacityFull {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("设计容量:"),
					valueColor.Sprint(formatMilliwattHours(battery.Capacity))))
			}

			// Voltage and power
			if battery.Voltage > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("电压:"),
					valueColor.Sprintf("%.2f V", battery.Voltage)))
			}

			if battery.PowerNow > 0 {
				powerLabel := "功耗:"
				if battery.IsCharging {
					powerLabel = "充电功率:"
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint(powerLabel),
					valueColor.Sprintf("%.2f W", float64(battery.PowerNow)/1000.0)))
			}

			// Temperature
			if battery.Temperature > 0 {
				tempColor := valueColor
				if battery.Temperature > 45 {
					tempColor = color.New(color.FgRed)
				} else if battery.Temperature > 40 {
					tempColor = color.New(color.FgYellow)
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("温度:"),
					tempColor.Sprintf("%.1f°C", battery.Temperature)))
			}

			// Cycle count
			if battery.CycleCount > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("循环次数:"),
					valueColor.Sprintf("%d", battery.CycleCount)))
			}

			// Vendor and technology
			if battery.Vendor != "" {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("制造商:"),
					valueColor.Sprint(battery.Vendor)))
			}

			if battery.Technology != "" {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("技术:"),
					valueColor.Sprint(battery.Technology)))
			}

			if battery.SerialNumber != "" {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("序列号:"),
					valueColor.Sprint(battery.SerialNumber)))
			}
		}

		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n"))
	}

	// GPU information
	if info.GPU != nil && len(info.GPU.GPUs) > 0 {
		sb.WriteString("\n")
		sb.WriteString(headerColor.Sprintf("┌─ 显卡(GPU) ──────────────────────────────────────────────────┐\n"))
		for _, gpu := range info.GPU.GPUs {
			sb.WriteString(fmt.Sprintf("│ %s\n", valueColor.Sprintf("GPU %d: %s", gpu.Index, gpu.Name)))

			if gpu.Vendor != "" {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("制造商:"), valueColor.Sprint(gpu.Vendor)))
			}

			if gpu.Driver != "" {
				driverStr := gpu.Driver
				if gpu.DriverVersion != "" {
					driverStr = fmt.Sprintf("%s (v%s)", gpu.Driver, gpu.DriverVersion)
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("驱动:"), valueColor.Sprint(driverStr)))
			}

			if gpu.MemoryTotal > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("显存:"), valueColor.Sprint(gpu.MemoryFormatted)))
				if gpu.MemoryUsed > 0 {
					usedPercent := float64(gpu.MemoryUsed) / float64(gpu.MemoryTotal) * 100
					memBar := createProgressBar(usedPercent, 28)
					sb.WriteString(fmt.Sprintf("│   %-18s %s %s\n", labelColor.Sprint("显存使用:"),
						memBar, valueColor.Sprintf("%s (%.1f%%)", formatBytes(gpu.MemoryUsed), usedPercent)))
				}
			}

			if gpu.Temperature > 0 {
				tempColor := valueColor
				if gpu.Temperature > 70 {
					tempColor = color.New(color.FgRed)
				} else if gpu.Temperature > 60 {
					tempColor = color.New(color.FgYellow)
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("温度:"), tempColor.Sprintf("%d°C", gpu.Temperature)))
			}

			if gpu.Utilization > 0 {
				utilBar := createProgressBar(float64(gpu.Utilization), 28)
				sb.WriteString(fmt.Sprintf("│   %-18s %s %s\n", labelColor.Sprint("GPU利用率:"),
					utilBar, valueColor.Sprintf("%d%%", gpu.Utilization)))
			}

			if gpu.MemoryUtilization > 0 {
				memUtilBar := createProgressBar(float64(gpu.MemoryUtilization), 28)
				sb.WriteString(fmt.Sprintf("│   %-18s %s %s\n", labelColor.Sprint("显存利用率:"),
					memUtilBar, valueColor.Sprintf("%d%%", gpu.MemoryUtilization)))
			}

			if gpu.PowerDraw > 0 {
				powerStr := fmt.Sprintf("%.1f W", gpu.PowerDraw)
				if gpu.PowerLimit > 0 {
					powerStr = fmt.Sprintf("%.1f / %.1f W", gpu.PowerDraw, gpu.PowerLimit)
				}
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("功耗:"), valueColor.Sprint(powerStr)))
			}

			if gpu.ClockSpeed > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("核心频率:"), valueColor.Sprintf("%d MHz", gpu.ClockSpeed)))
			}

			if gpu.ClockSpeedMemory > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("显存频率:"), valueColor.Sprintf("%d MHz", gpu.ClockSpeedMemory)))
			}

			if gpu.FanSpeed > 0 {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("风扇转速:"), valueColor.Sprintf("%d%%", gpu.FanSpeed)))
			}

			if gpu.PCIBus != "" {
				sb.WriteString(fmt.Sprintf("│   %-18s %s\n", labelColor.Sprint("PCI总线:"), valueColor.Sprint(gpu.PCIBus)))
			}

			sb.WriteString("│\n")
		}
		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n"))
	}

	// 最近活动
	if info.Activity != nil {
		sb.WriteString("\n")
		sb.WriteString(headerColor.Sprintf("┌─ 最近活动 ───────────────────────────────────────────────────┐\n"))
		// 最近运行的程序
		if len(info.Activity.RecentProcesses) > 0 {
			sb.WriteString(fmt.Sprintf("│ %s\n", labelColor.Sprint("最近启动的进程:")))
			max := len(info.Activity.RecentProcesses)
			if max > 15 { max = 15 }
			for i := 0; i < max; i++ {
				p := info.Activity.RecentProcesses[i]
				ts := valueColor.Sprintf("%s", time.UnixMilli(p.CreateTime).Format("2006-01-02 15:04:05"))
				name := p.Name
				if name == "" { name = "(未知)" }
				sb.WriteString(fmt.Sprintf("│   [%s] %s (PID %d)\n", ts, valueColor.Sprint(name), p.PID))
			}
		}

		// 最近访问的文件
		if len(info.Activity.RecentFiles) > 0 {
			sb.WriteString(fmt.Sprintf("│ %s\n", labelColor.Sprint("最近访问的文件:")))
			max := len(info.Activity.RecentFiles)
			if max > 15 { max = 15 }
			for i := 0; i < max; i++ {
				f := info.Activity.RecentFiles[i]
				ts := valueColor.Sprintf("%s", f.OpenedTime.Format("2006-01-02 15:04:05"))
				disp := f.DisplayName
				if disp == "" { disp = f.Path }
				sb.WriteString(fmt.Sprintf("│   [%s] %s\n", ts, valueColor.Sprint(disp)))
			}
		}

		sb.WriteString(headerColor.Sprintf("└──────────────────────────────────────────────────────────────┘\n"))
	}

	return sb.String()
}

// createProgressBar creates a text progress bar
func createProgressBar(percent float64, width int) string {
	filled := int(percent / 100.0 * float64(width))
	if filled > width {
		filled = width
	}
	if filled < 0 {
		filled = 0
	}

	bar := strings.Repeat("█", filled) + strings.Repeat("░", width-filled)

	// Color the bar based on usage
	if percent > 90 {
		return color.New(color.FgRed).Sprint(bar)
	} else if percent > 70 {
		return color.New(color.FgYellow).Sprint(bar)
	}
	return color.New(color.FgGreen).Sprint(bar)
}

// truncate truncates a string to the specified length
func truncate(s string, length int) string {
	if len(s) <= length {
		return s
	}
	return s[:length-3] + "..."
}

// formatTime formats minutes into a human-readable time string
func formatTime(minutes int64) string {
	if minutes < 0 {
		return "calculating..."
	}
	if minutes == 0 {
		return "0 min"
	}

	hours := minutes / 60
	mins := minutes % 60

	if hours == 0 {
		return fmt.Sprintf("%d min", mins)
	}
	if mins == 0 {
		return fmt.Sprintf("%d hr", hours)
	}
	return fmt.Sprintf("%d hr %d min", hours, mins)
}

// formatMilliwattHours formats milliwatt-hours into a human-readable string
func formatMilliwattHours(mwh uint64) string {
	if mwh == 0 {
		return "0 mWh"
	}

	// Convert to watt-hours if >= 1000 mWh
	if mwh >= 1000 {
		wh := float64(mwh) / 1000.0
		return fmt.Sprintf("%.2f Wh", wh)
	}

	return fmt.Sprintf("%d mWh", mwh)
}

// (removed) createTable was unused — kept tablewriter usage available if needed in future
